"""
部门管理API端点
"""
from typing import Optional
from fastapi import APIRouter, Depends, HTTPException, status, Query, Body
from app.schemas.department import (
    DepartmentCreate, 
    DepartmentUpdate, 
    DepartmentResponse,
    DepartmentListResponse
)
from app.api.deps import get_current_user, get_db
from app.core.permissions import require_permission
from app.core.response import success_response, error_response, ApiResponse
from app.services.department_service import DepartmentService
from motor.motor_asyncio import AsyncIOMotorDatabase

router = APIRouter()


@router.get("", response_model=ApiResponse, summary="获取部门列表")
@router.get("/", response_model=ApiResponse, summary="获取部门列表")
async def get_departments(
    tree: bool = Query(False, description="是否返回树形结构"),
    include_users: bool = Query(False, description="是否包含用户数量"),
    current_user: dict = Depends(get_current_user),
    db: AsyncIOMotorDatabase = Depends(get_db)
):
    """
    获取部门列表
    支持返回树形结构
    """
    try:
        # 检查权限
        require_permission(current_user, "user:read")
        
        # 调用服务层获取部门列表
        departments = await DepartmentService.get_departments(
            db, 
            tree=tree, 
            include_users=include_users
        )
        
        return success_response(
            data={
                "items": departments,
                "total": len(departments)
            },
            message="获取部门列表成功"
        )
    except HTTPException:
        raise
    except Exception as e:
        return error_response(
            error_type="INTERNAL_ERROR",
            message=f"获取部门列表失败: {str(e)}",
            code=status.HTTP_500_INTERNAL_SERVER_ERROR
        )


@router.get("/tree", response_model=ApiResponse, summary="获取部门树")
async def get_department_tree(
    include_users: bool = Query(False, description="是否包含用户数量"),
    current_user: dict = Depends(get_current_user),
    db: AsyncIOMotorDatabase = Depends(get_db)
):
    """
    获取部门树形结构
    """
    try:
        # 检查权限
        require_permission(current_user, "user:read")
        
        # 调用服务层获取部门树
        departments = await DepartmentService.get_departments(
            db, 
            tree=True, 
            include_users=include_users
        )
        
        return success_response(
            data=departments,
            message="获取部门树成功"
        )
    except HTTPException:
        raise
    except Exception as e:
        return error_response(
            error_type="INTERNAL_ERROR",
            message=f"获取部门树失败: {str(e)}",
            code=status.HTTP_500_INTERNAL_SERVER_ERROR
        )


@router.get("/{department_id}", response_model=ApiResponse, summary="获取部门详情")
async def get_department(
    department_id: str,
    current_user: dict = Depends(get_current_user),
    db: AsyncIOMotorDatabase = Depends(get_db)
):
    """
    获取部门详情
    """
    try:
        # 检查权限
        require_permission(current_user, "user:read")
        
        # 调用服务层获取部门详情
        department = await DepartmentService.get_department(db, department_id)
        
        if not department:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="部门不存在"
            )
        
        return success_response(
            data=department,
            message="获取部门详情成功"
        )
    except HTTPException:
        raise
    except Exception as e:
        return error_response(
            error_type="INTERNAL_ERROR",
            message=f"获取部门详情失败: {str(e)}",
            code=status.HTTP_500_INTERNAL_SERVER_ERROR
        )


@router.post("", response_model=ApiResponse, summary="创建部门")
@router.post("/", response_model=ApiResponse, summary="创建部门")
async def create_department(
    department_in: DepartmentCreate,
    current_user: dict = Depends(get_current_user),
    db: AsyncIOMotorDatabase = Depends(get_db)
):
    """
    创建部门
    需要权限：user:create
    """
    try:
        # 检查权限
        require_permission(current_user, "user:create")
        
        # 调用服务层创建部门
        department = await DepartmentService.create_department(db, department_in)
        
        return success_response(
            data=department,
            message="创建部门成功"
        )
    except ValueError as e:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail=str(e)
        )
    except HTTPException:
        raise
    except Exception as e:
        return error_response(
            error_type="INTERNAL_ERROR",
            message=f"创建部门失败: {str(e)}",
            code=status.HTTP_500_INTERNAL_SERVER_ERROR
        )


@router.put("/{department_id}", response_model=ApiResponse, summary="更新部门")
async def update_department(
    department_id: str,
    department_in: DepartmentUpdate,
    current_user: dict = Depends(get_current_user),
    db: AsyncIOMotorDatabase = Depends(get_db)
):
    """
    更新部门信息
    需要权限：user:update
    """
    try:
        # 检查权限
        require_permission(current_user, "user:update")
        
        # 调用服务层更新部门
        department = await DepartmentService.update_department(
            db, 
            department_id, 
            department_in
        )
        
        return success_response(
            data=department,
            message="更新部门成功"
        )
    except ValueError as e:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail=str(e)
        )
    except HTTPException:
        raise
    except Exception as e:
        return error_response(
            error_type="INTERNAL_ERROR",
            message=f"更新部门失败: {str(e)}",
            code=status.HTTP_500_INTERNAL_SERVER_ERROR
        )


@router.delete("/{department_id}", response_model=ApiResponse, summary="删除部门")
async def delete_department(
    department_id: str,
    current_user: dict = Depends(get_current_user),
    db: AsyncIOMotorDatabase = Depends(get_db)
):
    """
    删除部门
    需要权限：user:delete
    注意：如果部门下有子部门或用户，将无法删除
    """
    try:
        # 检查权限
        require_permission(current_user, "user:delete")
        
        # 调用服务层删除部门
        await DepartmentService.delete_department(db, department_id)
        
        return success_response(
            message="删除部门成功"
        )
    except ValueError as e:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail=str(e)
        )
    except HTTPException:
        raise
    except Exception as e:
        return error_response(
            error_type="INTERNAL_ERROR",
            message=f"删除部门失败: {str(e)}",
            code=status.HTTP_500_INTERNAL_SERVER_ERROR
        )


@router.post("/{department_id}/move", response_model=ApiResponse, summary="移动部门")
async def move_department(
    department_id: str,
    move_data: dict = Body(None),
    current_user: dict = Depends(get_current_user),
    db: AsyncIOMotorDatabase = Depends(get_db)
):
    """
    移动部门（调整父部门或排序）
    需要权限：user:update
    """
    try:
        # 检查权限
        require_permission(current_user, "user:update")
        
        # 从请求体中获取参数
        new_parent_id = move_data.get("new_parent_id") if move_data else None
        new_order = move_data.get("new_order") if move_data else None
        
        # 调用服务层移动部门
        department = await DepartmentService.move_department(
            db, 
            department_id, 
            new_parent_id, 
            new_order
        )
        
        return success_response(
            data=department,
            message="移动部门成功"
        )
    except ValueError as e:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail=str(e)
        )
    except HTTPException:
        raise
    except Exception as e:
        return error_response(
            error_type="INTERNAL_ERROR",
            message=f"移动部门失败: {str(e)}",
            code=status.HTTP_500_INTERNAL_SERVER_ERROR
        )

